/**
 * Generate code from /{{projectName}}-user/src/main/java/{{packageName}}/core/{{modules}}/service/impl/{{entities@SQL}}ServiceImpl.java.hbs
 */
// @SkipOverwrite
package cn.ibizlab.core.open.service.impl;

import cn.ibizlab.core.ad.domain.SysDomain;
import cn.ibizlab.core.ad.service.SysDomainService;
import cn.ibizlab.core.authentication.service.SocialService;
import cn.ibizlab.core.open.client.EbsxFeignClient;
import cn.ibizlab.core.open.domain.OpenAccess;
import cn.ibizlab.core.open.filter.OpenAccessSearchContext;
import cn.ibizlab.util.common.CacheStore;
import cn.ibizlab.util.enums.Entities;
import cn.ibizlab.util.errors.BadRequestAlertException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;

import static cn.ibizlab.core.authentication.constants.AuthenticationConstant.*;

/**
 * 实体[开放接入] 服务对象接口实现
 *
 * @author generator
 */
@Slf4j
@Service("OpenAccessService")
public class OpenAccessServiceImpl extends AbstractOpenAccessService {

    @Autowired
    SocialService socialService;

    @Override
    public OpenAccess getById(Serializable id) {
        OpenAccess access = super.getById(id);
        if(access == null){
            try {
                List<OpenAccess> socialConfigList = this.searchCompatible(new OpenAccessSearchContext().setIdEQ((String)id)).getContent();
                if(!ObjectUtils.isEmpty(socialConfigList))
                    access = socialConfigList.get(0);
            }
            catch (Exception ex) {

            }

        }
        return access;
    }

    /**
     * 获取社交平台的认证/授权地址
     * 1. 获取社交平台认证配置 (AppId、AppSecret)
     * 2. 构造社交平台认证请求 (AuthRequest)
     * 3. 获取社交平台认证地址 (AuthRequest.authorize)
     * @return
     */
    @Override
    public OpenAccess getAuthorizationUri(String openAccessId) {

        //获取社交平台认证配置
        OpenAccess socialConfig = getSelf().getById(openAccessId);
        if (socialConfig == null || 1 == socialConfig.getDisabled())
            throw new BadRequestAlertException(String.format("未找到社交平台[%1$s]认证配置", openAccessId), Entities.OPEN_ACCESS.toString(), "OpenAccess not found");

        //获取社交平台认证地址
        String socialAuthorizeUrl = socialService.authorize(socialConfig);
        OpenAccess ret = new OpenAccess();
        socialConfig.copyTo(ret,false);

        ret.setSecretKey(null);
        ret.setAccessToken(null);
        ret.setRedirectUri(socialAuthorizeUrl);

        return ret;

    }


    @Override
    public boolean create(OpenAccess et) {
        if(ObjectUtils.isEmpty(et.getOpenType()) && !ObjectUtils.isEmpty(et.getPredefType())
                && !"custom".equalsIgnoreCase(et.getPredefType())) {
            et.setOpenType(et.getPredefType());
        }
        if(ObjectUtils.isEmpty(et.getOpenType()))
            throw new BadRequestAlertException("类型不能为空",Entities.OPEN_ACCESS.toString(), "OpenType not found");

        if(ObjectUtils.isEmpty(et.getId()) && !ObjectUtils.isEmpty(et.getDcDefault())
                && !ObjectUtils.isEmpty(et.getOpenType())) {
            String key = String.format("%s||%s"
                    ,et.getDcDefault(),et.getOpenType().toUpperCase());
            et.setId(DigestUtils.md5DigestAsHex(key.getBytes()));
        }

        return super.create(et);
    }

    @Override
    public boolean update(OpenAccess et) {
        CacheStore.getInstance().clearL2ByPattern("ibiz-cloud-clouddata-*--OpenAccess");
        CacheStore.getInstance().clearL2ByPattern("ibiz-cloud-clouddata-*--OpenUser");
        return super.update(et);
    }

    @Autowired
    @Lazy
    private EbsxFeignClient ebsxFeignClient;

    @Value("${systemsettings.cloudclientutil.clientid:aibizhi}")
    String clientId = "";

    @Value("${systemsettings.cloudclientutil.clientsecret:}")
    String clientSecret = "";


    @Autowired
    @Lazy
    private SysDomainService domainService;

    private String defaultDC;
    public String getDefaultDC() {
        if (!ObjectUtils.isEmpty(defaultDC))
            return defaultDC;
        List<SysDomain> domains = domainService.list(Wrappers.<SysDomain>lambdaQuery().select(SysDomain::getId).orderByAsc(SysDomain::getCreateTime));
        if(!ObjectUtils.isEmpty(domains)) {
            defaultDC = domains.get(0).getId();
        }
        return defaultDC;
    }

    @Override
    public OpenAccess sync(OpenAccess dto) {

        RequestContextHolder.resetRequestAttributes();
        ebsxFeignClient.syncOrganizationUnits(dto.getId(), getDefaultDC(), new HashMap<String, Object>(), clientId, clientSecret);
        return super.sync(dto);
    }
}